import { Category } from '@libs/db/models/category.model';
import { Injectable } from '@nestjs/common';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';

@Injectable()
export class CategoriesService {
  constructor(
    @InjectModel(Category)
    private readonly categoryModel: ReturnModelType<typeof Category>,
  ) {}

  create(category: Category) {
    return this.categoryModel.create(category);
  }

  async findAll(query: any) {
    let { size, currentPage } = query || {};
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.categoryModel
      .find()
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.categoryModel.countDocuments();
    return {
      items: res,
      total,
    };
  }

  findOne(id: string) {
    return this.categoryModel.findOne({ _id: id });
  }

  update(id: string, category: Category) {
    return this.categoryModel.updateOne({ _id: id }, category);
  }

  remove(id: string) {
    return this.categoryModel.deleteOne({ _id: id });
  }
}
